<template>
  <div class="energy-weather-container">
    <h1 class="page-title">风棱无叶卡门涡街震频捕手可视化平台</h1>

    <el-card class="select-card">
      <div class="select-row">
        <el-select v-model="selectedProvince" placeholder="请选择省份" @change="onProvinceChange" style="width: 180px;">
          <el-option v-for="item in provinces" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-select v-model="selectedCity" placeholder="请选择城市" @change="onCityChange" style="width: 180px; margin-left: 10px;">
          <el-option v-for="item in citys" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-select v-model="selectedArea" placeholder="请选择区县" @change="onAreaChange" style="width: 180px; margin-left: 10px;">
          <el-option v-for="item in areas" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
    </el-card>

    <el-row :gutter="24" v-if="weather">
      <el-col :span="12">
        <el-card class="weather-card">
          <template #header>
            <div class="card-header weather-title">
              实时天气数据（{{ fullLocationName }}）
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/天气状况.png" class="icon" />
                  天气状况
                </div>
              </template>
              {{ weather.text }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/温度.png" class="icon" />
                  温度
                </div>
              </template>
              {{ weather.temp }}℃
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/体感温度.png" class="icon" />
                  体感温度
                </div>
              </template>
              {{ weather.feelsLike }}℃
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/风向.png" class="icon" />
                  风向
                </div>
              </template>
              {{ weather.windDir }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/风速.png" class="icon" />
                  风速
                </div>
              </template>
              {{ weather.windSpeed }} km/h
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/风力等级图标.png" class="icon" />
                  风力等级
                </div>
              </template>
              {{ weather.windScale }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/相对湿度.png" class="icon" />
                  相对湿度
                </div>
              </template>
              {{ weather.humidity }}%
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/云量.png" class="icon" />
                  云量
                </div>
              </template>
              {{ weather.cloud || '--' }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/降水量.png" class="icon" />
                  降水量
                </div>
              </template>
              {{ weather.precip }} mm
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/大气压强.png" class="icon" />
                  大气压强
                </div>
              </template>
              {{ weather.pressure }} hPa
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/能见度.png" class="icon" />
                  能见度
                </div>
              </template>
              {{ weather.vis }} km
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/露点温度.png" class="icon" />
                  露点温度
                </div>
              </template>
              {{ weather.dew || '--' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="energy-card">
          <template #header>
            <div class="card-header energy-title">
              能源生产潜力
            </div>
          </template>
           <el-descriptions :column="1" border>
             <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/水能.png" class="icon" />
                  水能
                </div>
              </template>
              {{ hydroPower }} MWh
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/太阳能.png" class="icon" />
                  太阳能
                </div>
              </template>
              {{ solarPower }} MWh
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <img src="@/assets/weather/风能.png" class="icon" />
                  风能
                </div>
              </template>
              {{ windPower }} MWh
            </el-descriptions-item>
           </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="summary-card" v-if="weather">
      <div class="summary-title">该地区主要能源</div>
      <div class="main-energy">{{ mainEnergySource }}</div>
    </el-card>

  </div>
</template>

<script setup name="Index">
import { ref, onMounted, computed } from 'vue'
import { getProvince, getCity, getArea, getLocationId, getWeatherByLocationId } from '@/api/index'
import { ElMessage } from 'element-plus'

const provinces = ref([])
const citys = ref([])
const areas = ref([])

const selectedProvince = ref(null)
const selectedCity = ref(null)
const selectedArea = ref(null)

const weather = ref(null)
const locationId = ref('')
const fullLocationName = ref('')

// 能源计算（示例算法，可根据实际需求调整）
const hydroPower = computed(() => {
  // 水能计算
  const precip = parseFloat(weather.value?.precip || '0');
  const waterCount = 1000 * precip;
  // Assuming a constant height of 50m for the formula
  return weather.value ? (0.85 * 1000 * 9.81 * waterCount * 50 / 1000000).toFixed(3) : '0.000'
})
const solarPower = computed(() => {
  // 太阳能计算
  if (!weather.value) return '0.000';
  const cloud = parseFloat(weather.value.cloud || '0');
  let sunPower = 0;
  switch(weather.value.text) {
    case '晴':
      sunPower = 80 * (1 - cloud/100);
      break;
    case '多云':
      sunPower = 50 * (1 - cloud/100);
      break;
    case '阴':
      sunPower = 20 * (1 - cloud/100);
      break;
    default:
      sunPower = 10 * (1 - cloud/100);
  }
  return sunPower.toFixed(3);
})
const windPower = computed(() => {
  // 风能计算
  const windSpeed = parseFloat(weather.value?.windSpeed || '0');
  const wind = Math.pow(windSpeed, 3);
  // Assuming a constant rotor area of 5026.55 sqm, air density 1.225 kg/m^3, Cp 0.4, efficiency 0.85 for the formula
  return weather.value ? (wind * 0.5 * 1.225 * 5026.55 * 0.4 * 0.85) / 100000 .toFixed(3) : '0.000';
})

// 计算主要能源
const mainEnergySource = computed(() => {
  if (!weather.value) return ''
  const hydro = parseFloat(hydroPower.value)
  const solar = parseFloat(solarPower.value)
  const wind = parseFloat(windPower.value)

  const maxEnergy = Math.max(hydro, solar, wind)

  const sources = []
  if (maxEnergy > 0) { // Only consider if there's actual energy produced
    if (hydro === maxEnergy) sources.push('水能')
    if (solar === maxEnergy) sources.push('太阳能')
    if (wind === maxEnergy) sources.push('风能')
  }

  if (sources.length === 0) return '暂无数据'
  if (sources.length === 1) return sources[0]
  return sources.join('、') + ' (主要)'
})

onMounted(async () => {
  try {
    // Fetch provinces
    const provinceRes = await getProvince()
    provinces.value = provinceRes

    // Find Hunan province and set as default
    const hunanProvince = provinces.value.find(p => p.name === '湖南')
    if (hunanProvince) {
      selectedProvince.value = hunanProvince.id

      // Fetch cities for Hunan
      const cityRes = await getCity(hunanProvince.id)
      citys.value = cityRes

      // Find Changsha city and set as default
      const changshaCity = citys.value.find(c => c.name === '长沙市')
      if (changshaCity) {
        selectedCity.value = changshaCity.id

        // Fetch areas for Changsha
        const areaRes = await getArea(changshaCity.id)
        areas.value = areaRes

        // Find Changsha county and set as default
        const changshaArea = areas.value.find(a => a.name === '长沙县')
        if (changshaArea) {
          selectedArea.value = changshaArea.id

          // Set full location name and fetch weather
          fullLocationName.value = '中国-湖南省-长沙市-长沙县'
          const locId = await getLocationId(fullLocationName.value)
          locationId.value = locId
          const weatherRes = await getWeatherByLocationId(locId)
          weather.value = weatherRes
        } else {
          ElMessage.warning('未找到长沙县信息')
        }
      } else {
        ElMessage.warning('未找到长沙市信息')
      }
    } else {
      ElMessage.warning('未找到湖南省信息')
    }
  } catch (error) {
    console.error('Error fetching initial data:', error)
    ElMessage.error('加载地理位置和天气信息失败')
  }
})

async function onProvinceChange(provinceId) {
  selectedCity.value = null // Reset city
  selectedArea.value = null // Reset area
  citys.value = []
  areas.value = []
  weather.value = null
  locationId.value = ''
  fullLocationName.value = ''
  if (provinceId) {
    const res = await getCity(provinceId)
    citys.value = res
  }
}

async function onCityChange(cityId) {
  selectedArea.value = null // Reset area
  areas.value = []
  weather.value = null
  locationId.value = ''
  fullLocationName.value = ''
  if (cityId) {
    const res = await getArea(cityId)
    areas.value = res
  }
}

async function onAreaChange(areaId) {
  weather.value = null
  locationId.value = ''
  fullLocationName.value = ''
  if (areaId) {
    // Find the selected province, city, and area objects to get their names
    const provinceName = provinces.value.find(p => p.id === selectedProvince.value)?.name || ''
    const cityName = citys.value.find(c => c.id === selectedCity.value)?.name || ''
    const areaName = areas.value.find(a => a.id === areaId)?.name || ''

    // Concatenate the full location name
    const locationStr = `中国-${provinceName}-${cityName}-${areaName}`
    fullLocationName.value = locationStr

    // Query LocationId and then weather
    try {
      const locId = await getLocationId(locationStr)
      locationId.value = locId
      const weatherRes = await getWeatherByLocationId(locId)
      weather.value = weatherRes
    } catch (e) {
      ElMessage.error('获取天气信息失败')
      console.error('Error fetching weather:', e)
    }
  }
}

// Removed goTarget function as it seems unrelated to the current task.
// function goTarget(url) {
//   window.open(url, '__blank')
// }
</script>

<style scoped lang="scss">
.energy-weather-container {
  padding: 20px;
  background: #eaf6ff; /* Light blue background */
  min-height: 100vh;
  font-family: 'Arial', sans-serif; /* Example font */
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: bold;
}

.select-card {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.select-row {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  justify-content: center;
}

.el-select {
  margin: 0 10px;
}

.weather-card, .energy-card {
  background: #fff; /* Changed to white background */
  border-radius: 12px;
  padding: 0; /* Remove default card padding */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  height: 100%; /* Make cards same height */
}

.card-header {
    padding: 18px 20px;
    border-bottom: 1px solid #ebeef5;
    box-sizing: border-box;
    font-size: 18px;
    font-weight: bold;
    color: #303133;
}

.el-descriptions {
    margin-top: 20px; /* Add space below header */
}

.el-descriptions__header {
    display: none; /* Hide default header */
}

.cell-item {
  display: flex;
  align-items: center;
}

.icon {
  width: 20px; /* Smaller icons in descriptions */
  height: 20px;
  margin-right: 5px;
}

/* Adjust padding within description cells */
:deep(.el-descriptions__body .el-descriptions__cell) {
    padding: 12px 10px !important;
}

/* Add styles for the new summary card */
.summary-card {
  margin-top: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  text-align: center;
}

.summary-title {
  font-weight: bold;
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.main-energy {
  font-size: 24px;
  color: #409EFF; /* Element Plus Primary color */
  font-weight: bold;
}
</style>

